#!/usr/bin/env python3
import tempfile
import os
import json
import shutil
import subprocess

cwd = os.getcwd()

def load_changelog():
    with open('CHANGELOG', 'r') as f:
        clog = json.load(f)
    versions = clog['versions']
    latest = sorted(versions.keys())[-1]
    deses = versions[latest]
    return clog['baseline'], latest, deses

def main():
    # 预先创建输出目录并设置权限
    output_dir = os.path.join(cwd, 'output')
    os.makedirs(output_dir, exist_ok=True)
    subprocess.run(['chmod', '755', output_dir], check=True)
    
    subprocess.run(['apt-get', 'install', '-y', 'devscripts', 'debhelper', 'dh-python', 'python3-all', 'pybuild-plugin-pyproject'], check=True)
    
    with tempfile.TemporaryDirectory() as tmpdir:
        base, latest, deses = load_changelog()
        version = base+'-'+latest
        build_dir = os.path.join(tmpdir, 'openubmc-qemu-'+base)
        shutil.copytree('deb_build/', build_dir)

        # 添加prerm的权限
        prerm_path = os.path.join(build_dir, 'debian', 'prerm')
        if os.path.exists(prerm_path):
            print(f"Setting executable permissions for: {prerm_path}")
            subprocess.run(['chmod', '+x', prerm_path], check=True)
        else:
            print(f"Warning: prerm file not found at {prerm_path}")
        
        # 添加postrm的权限
        postrm_path = os.path.join(build_dir, 'debian', 'postrm')
        if os.path.exists(postrm_path):
            print(f"Setting executable permissions for: {postrm_path}")
            subprocess.run(['chmod', '+x', postrm_path], check=True)
        else:
            print(f"Warning: postrm file not found at {postrm_path}")
        
        subprocess.run(['sh', 'build_qemu.sh'], check=True)
        bin_dir = os.path.join(build_dir, 'usr/share/qemu/bin/')
        os.makedirs(bin_dir, exist_ok=True)
        shutil.copy('build/qemu-system-aarch64', bin_dir)
        version_file = os.path.join(bin_dir, 'openUBMC_version')
        with open(version_file, "w", encoding="utf-8") as f:
            f.write(version)
        os.chdir(build_dir)
        os.environ["DEBFULLNAME"] = 'openUBMC'
        os.environ["DEBEMAIL"] = 'cicd@public.openubmc.cn'
        pypi_version = latest.split('build')[0]+'.0'
        os.environ["qemu_pypi_version"] = pypi_version
        subprocess.run([
            'dch', '--create',
            '--package', 'openubmc-qemu',
            '--newversion', version,
            '--distribution', 'unstable',
            '--urgency', 'low',
            deses[0]
        ], check=True)
        for des in deses[1:]:
            subprocess.run([
                'dch', '--append',
                des
            ], check=True)
        subprocess.run(['dpkg-buildpackage', '-us', '-uc'], check=True)
        subprocess.run(['ls', '-al', tmpdir], check=True)
        shutil.rmtree(build_dir)
        shutil.copytree(tmpdir, output_dir, dirs_exist_ok=True)
        
        # 最终权限设置
        subprocess.run(['chmod', '-R', '755', output_dir], check=True)

if __name__ == "__main__":
    main()